package com.csist.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.csist.pojo.bo.BasicStudentInfoBo;
import com.csist.pojo.bo.LevelRegistrationBo;
import com.csist.pojo.bo.SpecificationClassInfoBo;
import com.csist.pojo.bo.UserInfoBo;
import com.csist.pojo.dto.BasicStudentInfoBoDTO;
import com.csist.pojo.po.basicInfoModule.EducationMethod;
import com.csist.pojo.po.basicInfoModule.EducationStatus;
import com.csist.pojo.po.basicInfoModule.LevelMajorInfo;
import com.csist.pojo.po.basicInfoModule.SpecificationMajorInfo;
import com.csist.service.bo.BasicStudentInfoBoService;
import com.csist.service.bo.impl.BasicStudentInfoBoServiceImpl;
import com.csist.util.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sun.deploy.security.BlockedDialog.show;

@WebServlet("/basicStudentInfo")
public class BasicStudentInfoBoServlet extends HttpServlet {
    private JSONObject jsonObject;
    private BasicStudentInfoBoService basicStudentInfoBoService = new BasicStudentInfoBoServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
//        这里如果request没有json字符串，则jsonObject为null（获取不到）
        jsonObject = JSONUtil.getJSONObject(request);
        if (jsonObject == null) {
            err(request, response);
            return;
        }
        String type = jsonObject.getString("type");
        if (type != null) {
            switch (type) {
                case "add":
                    add(request, response);
                    break;
                case "query":
                    show(request, response);
                    break;
                case "conditionalShow":
                    conditionalShow(request, response);
                    break;
                default:
                    err(request, response);
            }
        } else {
            err(request, response);
        }
    }

    private void conditionalShow(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        这里jsonObject可以直接get()获取数据。如：String type = jsonObject.getString("type");
        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer num = pageNum == null ? 1 : pageNum;
        Map<String, Object> map = new HashMap<>();

//        获取xml中的每页条数导航页数
        String pageSize = this.getServletContext().getInitParameter("pageSize");
        String navigatePages = this.getServletContext().getInitParameter("navigatePages");

//        这里需要获取前端数据，用jsonObject然后将获取到的数据存储在BasicStudentInfoBoDTO中
        JSONObject group = jsonObject.getJSONObject("queryGroup");
        System.out.println(group);
        BasicStudentInfoBoDTO boDTO = new BasicStudentInfoBoDTO();
//        获取模糊查询判断
        boDTO.setFuzzyQuery(group.getBoolean("fuzzy"));
//        声明学生基础信息对象
        BasicStudentInfoBo basicStudentInfoBo = new BasicStudentInfoBo();
        basicStudentInfoBo.setBsiSid(group.getString("specialtyNum"));//专修编号
//        boDTO.setBasicStudentInfoBo(basicStudentInfoBo);
//        System.out.println("这个专修编号为："+boDTO.getBasicStudentInfoBo().getBsiSid());
        basicStudentInfoBo.setBsiName(group.getString("studentName"));//学生姓名
        basicStudentInfoBo.setBsiGender(group.getInteger("studentGender"));//学生性别
//       专修年级
        String studentYear = group.getString("studentYear");
//        if (studentYear == null || studentYear.isEmpty()) {
//            err(request, response);
//            return;
//        }
////        类型转换"2022"转换成2022-01-01T00:00
//        LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(studentYear + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());

//        "^(1000|\\d{4})$"这里处理办法：前端这里只能传要么是String类型4位日期，要么空数据设置为"",正则1000开头或者4位数字结尾的字符串，即表示范围在1000年到9999年之间的年份。
        System.out.println("获取的studentYear：" + studentYear);
        System.out.println("接下来进行判断是否为空和4位日期了");
        if ("".equals(studentYear)) {
            System.out.println("studentYear为不匹配日期数据...");
            basicStudentInfoBo.setBsiYear(null);
        } else if (studentYear.matches("^(1000|\\d{4})$")) {
            LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(studentYear + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
            basicStudentInfoBo.setBsiYear(dateTime);
            System.out.println("bsiYear？？？？？？:" + basicStudentInfoBo.getBsiYear());
        } else {
            Boolean state = false;
            String msg = "无效日期,请选择正确日期。。。";
            statusMsg(request, response, state, msg);
            return;
        }
//        专修季度
        basicStudentInfoBo.setBsiSeason(group.getInteger("enterBatch"));
//        证件号码
        basicStudentInfoBo.setBsiCredential(group.getString("idNum"));
//        班级名称
        SpecificationClassInfoBo specificationClassInfoBo = new SpecificationClassInfoBo();
        specificationClassInfoBo.setSciName(group.getString("className"));
//        teacherName(班主任编号)
        UserInfoBo userInfoBo = new UserInfoBo();
        userInfoBo.setUiId(group.getInteger("teacherName"));
        specificationClassInfoBo.setUserInfoBo(userInfoBo);
        basicStudentInfoBo.setSpecificationClassInfoBo(specificationClassInfoBo);
//        学习状态
        EducationStatus educationStatus = new EducationStatus();
        educationStatus.setEsId(group.getInteger("learningState"));
        basicStudentInfoBo.setEducationStatus(educationStatus);
//    specialtyMajor（学生的专修专业）
        SpecificationMajorInfo specificationMajorInfo = new SpecificationMajorInfo();
        specificationMajorInfo.setSmiId(group.getInteger("specialtyMajor"));
        basicStudentInfoBo.setSpecificationMajorInfo(specificationMajorInfo);


//        学历层次，这里要区分专科和本科
        JSONArray educationalLevel = group.getJSONArray("educationalLevel");
        LevelRegistrationBo levelRegistrationBo = new LevelRegistrationBo();
        // 检查是否有足够的元素，并且第一个元素是否为true
        if (educationalLevel.size() == 1) {
            if (educationalLevel.getBoolean(0)) {
//                    System.out.println("第一个元素是true");
                levelRegistrationBo.setLrIsBachelor(true);
//                学历平台注册号
                levelRegistrationBo.setLrUestcId(group.getString("registrationNum"));
//                学历的准考证号（学历学号）
                levelRegistrationBo.setLrLevelAdmissionId(group.getString("examNum"));
//                    学历注册年份
                String ry1 = group.getString("registrationYear");
//                if (ry1 == null || ry1.isEmpty()) {
//                    err(request, response);
//                    return;
//                }
//                LocalDateTime registrationYear = LocalDateTime.of(LocalDateTime.parse(ry1 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
//                levelRegistrationBo.setLrLevelRegYear(registrationYear);

//                if (ry1.matches("^(1000|\\d{4})$")) {
//                    LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(ry1 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
//                    levelRegistrationBo.setLrLevelRegYear(dateTime);
//                } else {
//                    levelRegistrationBo.setLrLevelRegYear(null);
//                }
                if ("".equals(ry1)) {
                    System.out.println("studentYear为不匹配日期数据...");
                    levelRegistrationBo.setLrLevelRegYear(null);
                } else if (ry1.matches("^(1000|\\d{4})$")) {
                    LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(ry1 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
                    levelRegistrationBo.setLrLevelRegYear(dateTime);
                    System.out.println("lrLevelRegYear？？？？？？:" + levelRegistrationBo.getLrLevelRegYear());
                } else {
                    Boolean state = false;
                    String msg = "无效日期,请选择正确日期。。。";
                    statusMsg(request, response, state, msg);
                    return;
                }
//                    注册季度
                levelRegistrationBo.setLrLevelRegSeasion(group.getInteger("registrationBatch"));
//                    毕业年份
                String gy1 = group.getString("graduationYear");
//                if (gy1 == null || gy1.isEmpty()) {
//                    err(request, response);
//                    return;
//                }
//                LocalDateTime graduationYear = LocalDateTime.of(LocalDateTime.parse(gy1 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
//                levelRegistrationBo.setLrLevelGraduYear(graduationYear);

//                if (gy1.matches("^(1000|\\d{4})$")) {
//                    LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(gy1 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
//                    levelRegistrationBo.setLrLevelGraduYear(dateTime);
//                } else {
//                    levelRegistrationBo.setLrLevelGraduYear(null);
//                }
                if ("".equals(gy1)) {
                    System.out.println("studentYear为不匹配日期数据...");
                    levelRegistrationBo.setLrLevelGraduYear(null);
                } else if (gy1.matches("^(1000|\\d{4})$")) {
                    LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(gy1 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
                    levelRegistrationBo.setLrLevelGraduYear(dateTime);
                    System.out.println("lrLevelGraduYear？？？？？？:" + levelRegistrationBo.getLrLevelGraduYear());
                } else {
                    Boolean state = false;
                    String msg = "无效日期,请选择正确日期。。。";
                    statusMsg(request, response, state, msg);
                    return;
                }

//                    教学方式(学历类型)
                EducationMethod educationMethod = new EducationMethod();
                educationMethod.setEmId(group.getInteger("teachingMethod"));
                levelRegistrationBo.setEducationMethod(educationMethod);
//                    学历专业
                LevelMajorInfo levelMajorInfo = new LevelMajorInfo();
                levelMajorInfo.setLmiId(group.getInteger("educationMajor"));
                levelRegistrationBo.setLevelMajorInfo(levelMajorInfo);
//                    学历在校状态
                EducationStatus ues = new EducationStatus();
                ues.setEsId(group.getInteger("levelLearningStatus"));
                levelRegistrationBo.setEducationStatus(ues);
                basicStudentInfoBo.setUndergraduateLevelRegistrationBo(levelRegistrationBo);
                System.out.println("执行本科这里了");
                System.out.println(basicStudentInfoBo.getUndergraduateLevelRegistrationBo());

            } else {
//              System.out.println("第一个元素是false");
                levelRegistrationBo.setLrIsBachelor(false);
//                学历平台注册号
                levelRegistrationBo.setLrUestcId(group.getString("registrationNum"));
//                学历的准考证号（学历学号）
                levelRegistrationBo.setLrLevelAdmissionId(group.getString("examNum"));
//                    学历注册年份
                String ry2 = group.getString("registrationYear");
//                if (ry2 == null || ry2.isEmpty()) {
//                    err(request, response);
//                    return;
//                }
//                LocalDateTime registrationYear = LocalDateTime.of(LocalDateTime.parse(ry2 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
//                levelRegistrationBo.setLrLevelRegYear(registrationYear);

//                if (ry2.matches("^(1000|\\d{4})$")) {
//                    LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(ry2 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
//                    levelRegistrationBo.setLrLevelRegYear(dateTime);
//                } else {
//                    levelRegistrationBo.setLrLevelRegYear(null);
//                }

                if ("".equals(ry2)) {
                    System.out.println("studentYear为不匹配日期数据...");
                    levelRegistrationBo.setLrLevelRegYear(null);
                } else if (ry2.matches("^(1000|\\d{4})$")) {
                    LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(ry2 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
                    levelRegistrationBo.setLrLevelRegYear(dateTime);
                    System.out.println("lrLevelRegYear？？？？？？:" + levelRegistrationBo.getLrLevelRegYear());
                } else {
                    Boolean state = false;
                    String msg = "无效日期,请选择正确日期。。。";
                    statusMsg(request, response, state, msg);
                    return;
                }

//                    注册季度
                levelRegistrationBo.setLrLevelRegSeasion(group.getInteger("registrationBatch"));
//                    毕业年份
                String gy2 = group.getString("graduationYear");
//                if (gy2 == null || gy2.isEmpty()) {
//                    err(request, response);
//                    return;
//                }
//                LocalDateTime graduationYear = LocalDateTime.of(LocalDateTime.parse(gy2 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
//                levelRegistrationBo.setLrLevelGraduYear(graduationYear);

//                if (gy2.matches("^(1000|\\d{4})$")) {
//                    LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(gy2 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
//                    levelRegistrationBo.setLrLevelGraduYear(dateTime);
//                } else {
//                    levelRegistrationBo.setLrLevelGraduYear(null);
//                }

                if ("".equals(gy2)) {
                    System.out.println("studentYear为不匹配日期数据...");
                    levelRegistrationBo.setLrLevelGraduYear(null);
                } else if (gy2.matches("^(1000|\\d{4})$")) {
                    LocalDateTime dateTime = LocalDateTime.of(LocalDateTime.parse(gy2 + "-01-01T00:00", DateTimeFormatter.ISO_LOCAL_DATE_TIME).toLocalDate(), LocalDateTime.MIN.toLocalTime());
                    levelRegistrationBo.setLrLevelGraduYear(dateTime);
                    System.out.println("lrLevelGraduYear？？？？？？:" + levelRegistrationBo.getLrLevelGraduYear());
                } else {
                    Boolean state = false;
                    String msg = "无效日期,请选择正确日期。。。";
                    statusMsg(request, response, state, msg);
                    return;
                }

//                    教学方式(学历类型)
                EducationMethod educationMethod = new EducationMethod();
                educationMethod.setEmId(group.getInteger("teachingMethod"));
                levelRegistrationBo.setEducationMethod(educationMethod);
//                    学历专业
                LevelMajorInfo levelMajorInfo = new LevelMajorInfo();
                levelMajorInfo.setLmiId(group.getInteger("educationMajor"));
                levelRegistrationBo.setLevelMajorInfo(levelMajorInfo);
//                    学历在校状态
                EducationStatus ues = new EducationStatus();
                ues.setEsId(group.getInteger("levelLearningStatus"));
                levelRegistrationBo.setEducationStatus(ues);
                basicStudentInfoBo.setSpecialtyLevelRegistrationBo(levelRegistrationBo);
                System.out.println("执行专科这里了");
                System.out.println(basicStudentInfoBo.getSpecialtyLevelRegistrationBo());
            }
        } else {
            System.out.println("同时选择了true和false,不成立");
        }
        boDTO.setBasicStudentInfoBo(basicStudentInfoBo);

        PageHelper.startPage(num, Integer.parseInt(pageSize));
        List<BasicStudentInfoBo> list = basicStudentInfoBoService.trendsFindManyBasicStudentInfo(boDTO);
        if (list != null) {
            PageInfo<BasicStudentInfoBo> pageInfo = new PageInfo<>(list, Integer.parseInt(navigatePages));
            map.put("pagination", pageInfo);
            map.put("status", true);
            map.put("msg", "查询信息成功...");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        findNoData(request, response);
    }

    private void statusMsg(HttpServletRequest request, HttpServletResponse response, Boolean status, String msg) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("msg", msg);
        response.getWriter().write(JSON.toJSONString(map));
    }


    private void show(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        当jsonObject为空时
        if (jsonObject == null) {
            err(request, response);
            return;
        }

        Integer pageNum = jsonObject.getInteger("pageNum");
        Integer num = pageNum == null ? 1 : pageNum;
        Map<String, Object> map = new HashMap<>();

//        获取xml中的每页条数导航页数
        String pageSize = this.getServletContext().getInitParameter("pageSize");
        String navigatePages = this.getServletContext().getInitParameter("navigatePages");
//        这里需要先开启分页对象，再进行查询数据
        PageHelper.startPage(num, Integer.parseInt(pageSize));

        List<BasicStudentInfoBo> list = basicStudentInfoBoService.selectAllBasicStudentInfo();
//      ①传输数据（分页对象）     ②不为空 true，为空false      ③判断list是否为空：不为空，查询学生信息成功；空，暂无学生信息
        if (list != null) {
            PageInfo<BasicStudentInfoBo> pageInfo = new PageInfo<>(list, Integer.parseInt(navigatePages));
            map.put("pagination", pageInfo);
            map.put("status", true);
            map.put("msg", "查询信息成功...");
            response.getWriter().write(JSON.toJSONString(map));
            return;
        }
        findNoData(request, response);
    }

    private void add(HttpServletRequest request, HttpServletResponse response) {
    }

    private void err(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("status", false);
        map.put("msg", "传送了无效数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }

    private void findNoData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pagination", null);
        map.put("status", false);
        map.put("msg", "无匹配数据...");
        response.getWriter().write(JSON.toJSONString(map));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
